const User = require('../database/userDao');
const express = require('express')
const router = express.Router()
const authMiddleware = require('../middleware/auth');
const { jwtSecret } = require('../utils/jwt');
const jwt = require('jsonwebtoken');
// 用户登录
router.post('/login', async (req,res) => {
  try {
      const { username, password, usertype } = req.body;
      const user = await User.findByUsername(username);
      if (!user || user.user_type !== usertype) {
        return res.status(401).json({ error: '账号不存在或用户类型不匹配' });
      }
      if (user.status !== 'active') {
        return res.status(401).json({ error: '账号未激活或已被冻结' });
      }
      if (!(password === user.password)) {
        return res.status(401).json({ error: '密码错误' });
      }
      const token = jwt.sign(
        { userId: user.user_id, userType: user.user_type },
        jwtSecret,
        { expiresIn: '8h' }
      );
      return res.status(200).json({
        user_id: user.user_id,
        name: user.name,
        user_type: user.user_type,
        status: user.status,
        token
      });
  } catch (error) {
      console.log(error)
      res.status(500).json({ error: '服务器错误' });
  }
})
// 用户注册
router.post('/register', async (req,res) => {
    try {
      const { username, name, password, user_type, company, phone } = req.body;
      
      const existingUser = await User.findByUsername(username);
      if (existingUser) {
        return res.status(400).json({ error: '账号已存在' });
      }
      
      const hashedPassword = await bcrypt.hash(password, 10);
      const userData = { username, name, password: hashedPassword, user_type };
      
      if (user_type === 'customer') {
        userData.company = company;
        userData.phone = phone;
      }
      
      await User.create(userData);
      res.json({ message: '注册成功，等待审核' });
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
// 用户审核
router.put('/:user_id/approve',authMiddleware(['admin']),  async (req,res) => {
  try {
      const userId = req.params.user_id;
      const { status } = req.body;
      
      await User.updateStatus(userId, status);
      res.json({ message: '审核完成' });
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
// 用户状态
router.put('/:user_id/status', authMiddleware(['admin']), async (req,res) => {
  try {
      const userId = req.params.user_id;
      const { status } = req.body;
      
      await User.updateStatus(userId, status);
      res.json({ message: '状态更新成功' });
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
// 获取用户
router.get('/', authMiddleware(['admin']), async (req,res) => {
  try {
      const { user_type, keyword } = req.query;
      
      const users = await User.findAll(user_type, keyword);
      res.json(users);
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
module.exports = router